import React from 'react'
import styles from './GifInfo.css'
// import item from './item.json'
// import vib from './vib.json'
import { Modal, Tag } from 'antd'
import GifTags from './GifTags.js'
import moment from 'moment'
import universalFetch, { handleFetchError, LoginFetch } from 'store/modules/fetch'
const CheckableTag = Tag.CheckableTag
// let datas = item.filter((dd) => dd.Type === '0' && dd.Overview_id === '1').map((d, i) => {
// let datas = item.filter((dd) => dd.Overview_id === '1').map((d, i) => {
//   const vibItem = vib.filter((dd) => dd.Id === d.Channel_id)
//   d['name'] = vibItem[0].name || ''
//   d['value'] = vibItem[0].Dif_lim_3x || ''
//   if (d.Type === '0') {
//     d['unit'] = vibItem[0].Unit || ''
//   } else if (d.Type === '1') {
//     d['unit'] = 'mm'
//   } else if (d.Type === '3') {
//     d['unit'] = 'rpm'
//   }
//   return d
// })

type Props = {
   data: Object,
   cardData: Array<Object>,
   removeGifInfoModal: Function,
   goToCondition: Function,
   requestType: string, // 值是wx证明是小程序访问
}

type State = {
  OverViewData: Array<Object>,
  ViewDataDynamic: Array<Object>,
  overShow: boolean,
  mainHeight: string,
  data: Object,
  thisTime: string
}

class GidInfo extends React.Component {
  props: Props
  state: State
  interval: number
  getKmxData: Function
  getOverViewData: Function
  hideModal: Function
  closeToConditin: Function
  changeOverView: Function
  constructor (props: Props) {
    super(props)
    this.state = {
      OverViewData: [],
      ViewDataDynamic: [],
      overShow: true,
      mainHeight: '',
      data: this.props.data,
      thisTime: ''
    }
    this.getKmxData = this.getKmxData.bind(this)
    this.getOverViewData = this.getOverViewData.bind(this)
    this.hideModal = this.hideModal.bind(this)
    this.closeToConditin = this.closeToConditin.bind(this)
    this.changeOverView = this.changeOverView.bind(this)
  }

  componentWillMount () {
    const { data } = this.state
    this.getOverViewData(data)
    const component = this
    clearInterval(this.interval)
    this.interval = setInterval(function () {
      component.getKmxData(data)
    }, 5000)
  }

  // componentWillReceiveProps (nextProps) {
  //   if (!R.equals(nextProps, this.props)) {
  //     clearInterval(this.interval)
  //     this.getOverViewData(nextProps.data)
  //     const component = this
  //     this.interval = setInterval(function () {
  //       component.getKmxData(nextProps.data)
  //     }, 5000)
  //   }
  // }

  componentWillUnmount () {
    clearInterval(this.interval)
  }

  changeOverView (data, checked) {
    if (!checked) return  // 如果选中的是自己就不执行
    const component = this
    clearInterval(component.interval)
    component.getOverViewData(data)
    component.interval = setInterval(function () {
      component.getKmxData(data)
    }, 5000)
    component.setState({
      data: data
    })
  }

  getOverViewData (data) {
    const mainHeight = document.body.clientHeight - 130 // 弹出层的高度
    const { requestType } = this.props
    let api = `${__SERVICE_API__}`
    if (requestType === 'wx') {
      api = `${__WXSERVICE_API__}`
    }
    universalFetch(`${api}device/devices/${data.id}/overview`)
      .then((res) => res.json())
      .then((json) => {
        if (json.code !== 200000) {
          throw new Error(JSON.stringify({ code: json.code, message: json.message }))
        }
        const ret = json.result.map((d, i) => {
          d['top'] = d.y
          d['left'] = d.x
          d['value'] = '-'
          // if (d.variable === 'value') {
          //   d['unit'] = 'mm'
          // } else if (d.variable === 'speed') {
          //   d['unit'] = 'rpm'
          // } else {
          //   d['unit'] = 'μm'
          // }
          return d
        })
        const result = json.result
        this.setState({
          mainHeight: mainHeight,
          OverViewData: ret,
          ViewDataDynamic: json.result.map((d, i) => {
            let ob = {}
            ob['data'] = data
            ob['mes'] = ret[i]
            ob['value'] = '-'
            return ob
          })
        }, () => {
          // tcs 先请求一次历史数据（为每个指标都有数据）[tcs所有指标的通道和fieldGroup都相同]
          if (data.dataSource === 'TCS') {
            const deviceNo = data.deviceNo.split('_')
            let postBody2 = {
              fieldGroup: result[0].fieldgroupId,
              // fields: ['PDI113001_31','$PDI113001_31_state'],
              fields: result.map((d, i) => { return d.variable }),
              coValueFilter: {
                idFieldFilter: {
                  factory_id: { '$eq': String(deviceNo[0]) },
                  equipment_id: { '$eq': String(deviceNo[1]) },
                  machine_id: { '$eq': String(deviceNo[2]) },
                  datatype: { '$eq': '1' },
                  '$or': [{ 'channel_id': { '$eq': String(result[0].channelId) } }]
                }
              },
              timeRange: {
                start: moment().subtract(1, 'd').format('YYYY-MM-DDTHH:mm:ss.SSSZ'),
                end: moment().format('YYYY-MM-DDTHH:mm:ss.SSSZ')
              },
              valueFilters: [
                  { '$default': { '$or': [{ '$gt': -1000000 }] } }
              ],
              order: [{ '$default': 'desc' }],
              size: 1,
              page: 1
            }
            // LoginFetch(`${__KMX_API__}data-rows`, { // rows不能用是因为取出的值是同一个时间点，但不同指标有值的时间点不一定相同
            let api = `${__KMX_API__}`
            if (requestType === 'wx') {
              api = `${__WXKMX_API__}`
            }
            LoginFetch(`${api}data-streams`, {
              method: 'POST',
              headers: {
                'Content-Type': 'application/json'
              },
              body: JSON.stringify(postBody2)
            })
            .then(res => {
              return res.json()
            })
            .then((json) => {
              // console.log('历史——————————————————————————————————————');
              // console.log(json.results);
              this.setState({
                ViewDataDynamic: json.results.map((d, i) => {
                  let ob = {}
                  ob['data'] = data
                  ob['mes'] = ret[i]
                  ob['value'] = d.streams.length > 0 ? d.streams[0][1] : '-'
                  return ob
                })
              })
            })
            .catch((err) => {
              console.error(err)
            })
          }
          // tcs请求历史数据结束
          this.getKmxData(data)
        })
      })
      .catch((error) => {
        handleFetchError(error)
        console.error(error)
      })
  }

  getKmxData (data) { // 总貌图
    const component = this
    const monitors = this.state.OverViewData
    // 以前的版本从data-streams中取值
    // const res = monitors.map((monitorsItem, i) => {
    //   const deviceNo = data.deviceNo.split('_')
    //   let postBody = {
    //     fieldGroup: monitorsItem.fieldgroupId,
    //     fields: [monitorsItem.variable],
    //     coValueFilter: {
    //       idFieldFilter: {
    //         factory_id: { '$eq': String(deviceNo[0]) },
    //         equipment_id: { '$eq': String(deviceNo[1]) },
    //         machine_id: { '$eq': String(deviceNo[2]) },
    //         datatype: { '$eq': '1' },
    //         '$or': [{ 'channel_id': { '$eq': String(monitorsItem.channelId) } }]
    //       }
    //     },
    //     timeRange: {
    //       // start: moment().subtract(1, 'days'),
    //       // end: nowTime
    //       start:'now-10m',
    //       end: 'now'
    //     },
    //     order: [{ '$default': 'desc' }],
    //     size: 1,
    //     page: 1
    //   }
    //   if (monitorsItem.En === 'c_sta') { // 如果是过程量就请求channel_type = 1 的值
    //     postBody.coValueFilter.idFieldFilter['channel_type'] = { '$eq': '1' }
    //   }
    //   return LoginFetch(`${__KMX_REAL_TIME_API__}data-streams`, {
    //     method: 'POST',
    //     headers: {
    //       'Content-Type': 'application/json'
    //     },
    //     body: JSON.stringify(postBody)
    //   }).then((res) => res.json())
    // })
    // 最新版本从data-rows中取值(可以请求到指标的阈值规则)
    const res = monitors.map((monitorsItem, i) => {
      const deviceNo = data.deviceNo.split('_')
      const state = '$' + monitorsItem.variable + '_state'
      // let postBody = {
      //   fieldGroup: monitorsItem.fieldgroupId,
      //   fields: [monitorsItem.variable, state],
      //   coValueFilter: {
      //     idFieldFilter: {
      //       factory_id: { '$eq': String(deviceNo[0]) },
      //       equipment_id: { '$eq': String(deviceNo[1]) },
      //       machine_id: { '$eq': monitorsItem.kmxMachineId === undefined
      //       ? String(deviceNo[2]) : monitorsItem.kmxMachineId },
      //       datatype: { '$eq': '1' },
      //       '$or': [{ 'channel_id': { '$eq': String(monitorsItem.channelId) } }] // overview
      //     }
      //   },
      //   timeRange: {
      //     start: data.rootId === 244 ? 'now-60m' : 'now-30m',
      //     end: 'now'
      //   },
      //   order: 'desc',
      //   size: 1000,
      //   page: 1
      // }
      const { requestType } = this.props
      let api = `${__KMX_REAL_TIME_API__}`
      if (requestType === 'wx') {
        api = `${__WXKMX_REAL_TIME_API__}`
      }
      let url = `${__KMX_TSDB_QUERY_URL__}kmx/tsdb/query?type=rows`
      const token = localStorage.getItem('asset_token')
      let header = {
        'Content-Type': 'application/json',
        'X-Auth':token
      }
      let postBody = {
        'tsTable' : `${monitorsItem.fieldgroupId}_m${monitorsItem.kmxMachineId === undefined
          ? String(deviceNo[2]) : monitorsItem.kmxMachineId}`,
        // 'allCol' : 'true',
        'startTime' : data.rootId === 244 ? moment().subtract(30, 'm').unix() : (moment().subtract(30, 'm').unix()),
        // 'endTime' : moment().unix(),
        'queryConditions' : [
          {
            'colName' : 'factory_id',
            'condition' : 'eq',
            'value' : String(deviceNo[0])
          },
          {
            'colName' : 'equipment_id',
            'condition' : 'eq',
            'value' : String(deviceNo[1])
          },
          {
            'colName' : 'machine_id',
            'condition' : 'eq',
            'value' : monitorsItem.kmxMachineId === undefined
              ? String(deviceNo[2]) : monitorsItem.kmxMachineId
          },
          {
            'colName' : 'datatype',
            'condition' : 'eq',
            'value' : 1
          },
          {
            'colName' : 'channel_id',
            'condition' : 'in',
            'value' : [monitorsItem.channelId]
          }
        ],
        orderCondition : {
          'colName' : 'time',
          'direct' : 'desc'
        },
        cols : [monitorsItem.variable]
      }
      if (monitorsItem.fieldgroupId === 'c_sta') { // 如果是过程量就请求channel_type = 1 的值
        header = {
          'Content-Type': 'application/json'
        }
        postBody = {
          fieldGroup: monitorsItem.fieldgroupId,
          fields: [monitorsItem.variable, state],
          coValueFilter: {
            idFieldFilter: {
              factory_id: { '$eq': String(deviceNo[0]) },
              equipment_id: { '$eq': String(deviceNo[1]) },
              machine_id: { '$eq': monitorsItem.kmxMachineId === undefined
              ? String(deviceNo[2]) : monitorsItem.kmxMachineId },
              datatype: { '$eq': '1' },
              '$or': [{ 'channel_id': { '$eq': String(monitorsItem.channelId) } }] // overview
            }
          },
          timeRange: {
            start: data.rootId === 244 ? 'now-60m' : 'now-30m',
            end: 'now'
          },
          order: 'desc',
          size: 1000,
          page: 1
        }
        postBody.coValueFilter.idFieldFilter['channel_type'] = { '$eq': '1' }
        url = `${api}data-rows`
      }
      if (monitorsItem.fieldgroupId === 'c_vib') {
        header = {
          'Content-Type': 'application/json'
        }
        postBody = {
          fieldGroup: monitorsItem.fieldgroupId,
          fields: [monitorsItem.variable, state],
          coValueFilter: {
            idFieldFilter: {
              factory_id: { '$eq': String(deviceNo[0]) },
              equipment_id: { '$eq': String(deviceNo[1]) },
              machine_id: { '$eq': monitorsItem.kmxMachineId === undefined
              ? String(deviceNo[2]) : monitorsItem.kmxMachineId },
              datatype: { '$eq': '1' },
              '$or': [{ 'channel_id': { '$eq': String(monitorsItem.channelId) } }] // overview
            }
          },
          timeRange: {
            start: data.rootId === 244 ? 'now-60m' : 'now-30m',
            end: 'now'
          },
          order: 'desc',
          size: 1000,
          page: 1
        }
        url = `${api}data-rows`
      }

      return LoginFetch(url, {
        method: 'POST',
        headers: header,
        body: JSON.stringify(postBody)
      }).then((res) => res.json())
    })
    Promise.all(res).then((jsons) => {
      let results = []
      jsons.map((d, i) => {
        // results.push(...d.results) // 有两个channel-type
        // results.push(d.result)
        if (d.result !== undefined) {
          results.push(d.result[0])
        } else {
          results.push(d.results[0])
        }
        // results.push(d.results[0])
      })
      if (results && results.length > 0) {
        let ViewDataDynamic = []
        let thisTime = this.state.thisTime
        results.map((d, i) => {
          d['data'] = data
          d['mes'] = monitors[i]
          // d['value'] = '-'
          d['value'] = component.state.ViewDataDynamic[i].value // 默认是以前的数据，有最新值后再替换
          d['limitType'] = ''
          // data-streams
          // if (d.streams && d.streams.length > 0) {
          //   d['value'] = d.streams[0][1]
          // } else {
          //   d['value'] = 0
          // }
          // data-rows
          // 找到最新的那个数据>-1000000的值显示（如果没有就是-）
          // let valueEmpty = true // 判断是否取到值，true是空值
          for (var ii = 0; ii < d.rows.length; ii++) {
            if (d.rows[ii]['values'] && d.rows[ii]['values'][0] > -1000000) {
              // 有值的指标的时间戳
              const timestamp = d.rows[ii]['timestamp']
              if (timestamp > thisTime) {
                thisTime = timestamp
              }
              // 取到第一个有值的数
              d['value'] = d.rows[ii]['values'][0]
              d['limitType'] = d.rows[ii]['values'][1]
              // valueEmpty = false
              break
            }
          }
          // console.log(valueEmpty + '空');
          ViewDataDynamic.push(d)
        })
        component.setState({
          ViewDataDynamic:ViewDataDynamic,
          thisTime: thisTime
        })
      }
    })
  }

  hideModal () {
    this.setState({
      overShow: false
    })
    this.props.removeGifInfoModal()
  }

  closeToConditin (data) {
    this.hideModal()
    this.props.goToCondition(data)
  }

  render () {
    const { cardData, requestType } = this.props
    const { data } = this.state
    let title = ['总貌图（' + data.customerName + ' / ' + data.name + '）']
    cardData.map((d, i) => {
      // title.push(<Tag disabled onClick={function () { component.changeOverView(d) }}>{d.name}</Tag>)
      title.push(<CheckableTag
        key={d.name}
        checked={d.name === data.name}
        onChange={checked => this.changeOverView(d, checked)}
      >
        {d.name}
      </CheckableTag>)
    })
    const { ViewDataDynamic, mainHeight, thisTime } = this.state
    // 时间显示(目前先不显示)
    let timeLabel = ''
    if (thisTime) {
      timeLabel = moment(this.state.thisTime).format('YYYY-MM-DD HH:mm:ss')
    }
    // render 内容
    const thisBody = (<div className={styles['main']} style={{ height: requestType === 'wx' ? '100%' : mainHeight }}>
      <div className={styles['infoImgCon']}>
        {
          // <label className={styles['infoTime']}>{timeLabel}</label>
        }
        {
          ViewDataDynamic.map((d, i) => {
            return <GifTags key={i} data={d} goToCondition={this.closeToConditin} />
          })
        }
        <img src={data.overviewUrl} className={styles['infoImg']} />
      </div>
    </div>)
    const thisBodyCon = requestType === 'wx' ? thisBody : <Modal
      title={title}
      width={'96%'}
      style={{ top: 20 }}
      visible={this.state.overShow}
      onCancel={this.hideModal}
      footer={null}
    >
      { thisBody }
    </Modal>
    return (
      thisBodyCon
    )
  }
}
export default GidInfo
